package hxy.dragon.location_record;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.navigation.fragment.NavHostFragment;

import hxy.dragon.location_record.databinding.FragmentFirstBinding;
import hxy.dragon.location_record.tencent.LocationService;
import hxy.dragon.location_record.util.Constant;

public class FirstFragment extends Fragment {

    private BroadcastReceiver receiver;
    private FragmentFirstBinding binding;
    private TextView mStatus;
    private String record;

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        Toast.makeText(MainActivity.getAppContext(), "FirstFragment onViewCreated", Toast.LENGTH_SHORT).show();

        mStatus = (TextView) getView().findViewById(R.id.first_location_view);
        mStatus.setText(record);

        binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }

    @Override
    public void onAttach(@NonNull Context context) {
//        Toast.makeText(MainActivity.getAppContext(), "FirstFragment onAttach", Toast.LENGTH_SHORT).show();

        //注册广播，接收service的广播消息。
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                String locationInfo = intent.getExtras().getString(Constant.LOCATION_INFO);
                record = locationInfo;
                //传递经纬度，在界面上显示。
                mStatus.setText(record);
            }
        };
        IntentFilter filter = new IntentFilter(Constant.BROADCAST);
        context.registerReceiver(receiver, filter);
        super.onAttach(context);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
//        Toast.makeText(MainActivity.getAppContext(), "FirstFragment onDestroyView", Toast.LENGTH_SHORT).show();
    }


}